﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Ext.Net;
using Sio.Mdm.Web.Controls;
using Sio.Mdm.Entities;

namespace IDM.Web
{
    public partial class AddUser : Sio.Mdm.Web.Controls.Page
    {
        #region Properties

        #region IsEdit
        private bool IsEdit
        {
            get
            {
                return UserID > -1;
            }
        } 
        #endregion

        #region UserID
        private int UserID
        {
            get
            {
                int id = -1;
                return Int32.TryParse(Request.QueryString["id"], out id) ? id : -1;
            }
        }  
        #endregion

        #endregion

        #region Methods

        protected override void OnLoad(EventArgs e)
        {
            if (IsEdit && !ExtNet.IsAjaxRequest)
            {
                LoadUser();
            }

            base.OnLoad(e);
        }        

        #region OnDialogButton
        protected override void OnDialogButton(DialogButtonEventArgs e)
        {
            IDM.Types.User user = EntityFactory.CreateInstance<Types.User>();

            if (IsEdit)
            {
                user.Load(UserID);
            }

            user.Name = Username.Text;

            if (!IsEdit)
            {
                if (user.Exists())
                {
                    e.Success = false;
                    e.ErrorText = "User already exists!";
                    return;
                }

                if (String.IsNullOrEmpty(Password1.Text))
                {
                    e.Success = false;
                    e.ErrorText = "Passwords must be set!";
                    return;
                }
            }

            if (!String.IsNullOrEmpty(Password1.Text))
            {
                if (Password1.Text != Password2.Text)
                {
                    e.Success = false;
                    e.ErrorText = "Passwords does not match!";
                    return;
                }

                user.Password = Password1.Text;
            }

            e.Success = user.Update();

            if (!e.Success)
            {
                e.ErrorText = user.Error.ToString();
            }

            base.OnDialogButton(e);
        }  
        #endregion

        #region LoadUser
        private void LoadUser()
        {
            Types.User user = EntityFactory.CreateInstance<Types.User>();

            if (user.Load(UserID))
            {
                Username.Text = user.Name;
            }
        } 
        #endregion

        #endregion
    }
}
